<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        排班方案
        <span
          v-if="statusName != ''"
          class="patCircle"
          :style="{ background: statusColor }"
          >{{ statusName }}</span
        >
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="titleName"
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend" style="color: red"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <editForm
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="formData"
            ><template #advanceShiftTime="{ item, editFormInfo }">
              <div class="dayInput">
                <el-input-number
                  style="flex: 2; margin-right: 20px"
                  size="mini"
                  v-model="editFormInfo.advanceShiftTime"
                  :step="1"
                  :min="0"
                  :disabled="item.disabled"
                  controls-position="right"
                  placeholder="请输入"
                  class="w100"
                ></el-input-number>
                <el-select
                  style="flex: 1"
                  size="mini"
                  v-model="editFormInfo.advanceShiftUnit"
                  placeholder="请选择"
                  :disabled="item.disabled"
                >
                  <el-option
                    v-for="item in timeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div> </template
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <span class="titleLine"></span>
            排班明细
          </template>
          <div class="scheduleList">
            <scheduleDetailList
              :allInfo="formData"
              :currentOrg="currentOrg"
              @handleEndTime="handleEndTime"
              ref="scheduleDetailList"
            ></scheduleDetailList>
          </div>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      :title="''"
      :show.sync="show"
      v-if="show"
      :btnText="['继续保存', '取消']"
      @doSubmit="doSubmit"
      @doClose="() => (show = false)"
      width="30%"
    >
      <div style="min-height: 200px" class="wraning">
        <h3>检测到以下排班方案的时间可能存在冲突，是否确认保存?</h3>
        <ul>
          <li
            v-for="(item, index) in scheduleList"
            :key="index"
            class="text"
            @click="clickQuery(item)"
          >
            {{ item.name }}[点击查看]
          </li>
        </ul>
      </div>
    </dialogPublic>
    <dialogPublic
      :title="'复用排班方案'"
      :show.sync="showMultiplexing"
      v-if="showMultiplexing"
      :btnText="['确定', '取消']"
      @doSubmit="multiplexingSubmit"
      @doClose="() => (showMultiplexing = false)"
    >
      <copyDialog :formData="formData" ref="copyDialog"></copyDialog>
    </dialogPublic>
  </div>
</template>
<script>
import {
  querySchedulPlanDetail,
  addOrUpdateSchedulPlan,
  deleteSchedulPlan,
  hasDuplicate,
  stopOrStartSchedulPlan, //停用或启用
} from "@/api/operationManagement/runningSchedule.js";
import scheduleDetailList from "./scheduleDetailList.vue";
import copyDialog from "./copyDialog.vue";
export default {
  components: {
    scheduleDetailList,
    copyDialog
  },
  data() {
    return {
      statusColor: "",
      statusName: "",
      activeNames: ["1", "2"],
      titleName: "",
      showInput: false,
      hideBtn: false,
      titleEdit: true,
      currentOrg: "",
      show: false,
      showMultiplexing: false,
      scheduleList: [],
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      basicConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "值班单位",
            prop: "deptName",
            propArr: "deptArr",
            idsStr: "deptId",
            type: "dept-select", //类型
            required: true,
            option: [],
            multiple: false,
            disabled: false,
            methods: (obj) => {
              this.currentOrg = obj[0].id;
            },
            span: 6,
          },
          {
            label: "值班地点",
            prop: "locationName",
            propArr: "locationArr",
            idsStr: "locationId",
            type: "location-select",
            option: [],
            multiple: false,
            required: true,
            disabled: false,
            span: 6,
          },
          {
            label: "排班开始时间",
            prop: "startTime",
            type: "datetime",
            span: 6,
            required: true,
            disabled: true,
          },
          {
            label: "排班结束时间",
            prop: "endTime",
            type: "datetime",
            span: 6,
            required: false,
            disabled: true,
          },
          {
            label: "班别方案",
            prop: "classesName",
            type: "text",
            span: 6,
            required: true,
            disabled: true,
          },
          {
            label: "值班人员类型",
            prop: "staffType",
            type: "select",
            span: 6,
            required: false,
            disabled: true,
            selectOption: this.$store.getters.dirtData("operation_staff_type"),
          },
          {
            label: "提前交班时间",
            prop: "advanceShiftTime",
            type: "text",
            span: 6,
            required: false,
            disabled: false,
            methods: (val) => {},
          },
          {
            label: "自动交接班",
            prop: "autoSwitch",
            type: "radio",
            span: 6,
            required: true,
            disabled: false,
            radioOption: [
              { label: "是", value: 1 },
              { label: "否", value: 0 },
            ],
          },
        ],
      },
      formData: {},
      timeOptions: this.$store.getters.dirtData("operation_advance_unit"),
      checkItemList: [],
      paramsItemList: [],
      disableHandover: false,
      remainingTime: "",
      defaultTime:10,
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "启用",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.statusName != "停用",
          content: !this.$store.getters.isBtnAuth("enable")
            ? "未授权功能"
            : this.remainingTime,
          disabled: !this.$store.getters.isBtnAuth("enable") || this.disableHandover,
          methods: () => {
            this.StartPlan();
          },
        },
        {
          text: "停用",
          icon: "el-icon-video-pause",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.statusName != "启用",
          content: !this.$store.getters.isBtnAuth("deactivate")
            ? "未授权功能"
            : this.remainingTime,
          disabled:
            !this.$store.getters.isBtnAuth("deactivate") || this.disableHandover,
          methods: () => {
            this.stopPlan();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide: ["details", "perform"].includes(this.pageType),
          content: !this.$store.getters.isBtnAuth("save")
            ? "未授权功能"
            : this.remainingTime,
          disabled: !this.$store.getters.isBtnAuth("save") || this.disableHandover,
          methods: () => {
            this.isHaveSameSchedule();
          },
        },
        {
          text: "复用",
          icon: "el-icon-document-copy",
          hide: ["perform", "add"].includes(this.pageType)||!this.isYinChuan,
          content:  "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("copy") || this.disableHandover,
          methods: () => {
            this.showMultiplexing = true;
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide: ["perform", "add"].includes(this.pageType),
          content: !this.$store.getters.isBtnAuth("delete")
            ? "未授权功能"
            : this.remainingTime,
          disabled: !this.$store.getters.isBtnAuth("delete") || this.disableHandover,
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    isYinChuan(){
      return this.$store.getters.currentAppInfo.appCode == "EAM_YCSC";
    }
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    //初始化详情页
    init() {
      let { id, multiplexingId,pageType } = this.$route.query;
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          this.titleEdit = false;
        }
      }else if(multiplexingId){
        this.getMultiplexingDetail(multiplexingId);
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.$message.warning("名称不能为空");
      }
    },
    //设置结束时间
    handleEndTime(endTime) {
      this.$refs.basicForm.setFormItem("endTime", endTime);
    },
    // //获取复用方案详情
    // getMultiplexingDetail(id){
    //     querySchedulPlanDetail({ id: id }).then((res) => {
    //     if (res.code == 200) {
    //       let data = res.data;
    //       delete data.id;
    //       data.
    //       this.formData = res.data;
    //       this.titleName = this.formData.name;
    //       this.currentOrg = this.formData.deptId;
    //       let deptOption = [
    //         {
    //           label: this.formData.deptName,
    //           value: this.formData.deptId,
    //           id: this.formData.deptId,
    //         },
    //       ];
    //       let locationOption = [
    //         {
    //           label: this.formData.locationName,
    //           value: this.formData.locationId,
    //           id: this.formData.locationId,
    //         },
    //       ];
    //       setTimeout(() => {
    //         this.$refs.basicForm.setItemOption("deptName", deptOption);
    //         this.$refs.basicForm.setItemOption("locationName", locationOption);
    //         this.$refs.basicForm.setFormItem("deptArr", this.formData.deptId);
    //         this.$refs.basicForm.setFormItem(
    //           "locationArr",
    //           this.formData.locationId
    //         );
    //       }, 100);
    //       if (this.formData.staffType == "3") {
    //         this.$refs.basicForm.setItemArrRules({
    //           locationArr: {
    //             required: false,
    //           },
    //         });
    //       } else {
    //         this.$refs.basicForm.setItemArrRules({
    //           locationArr: {
    //             required: true,
    //             message: "请选择值班地点",
    //             trigger: "blur",
    //           },
    //         });
    //       }
    //     }
    //   });
    // },
    //获取标准详情
    getDetails(id) {
      querySchedulPlanDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.titleName = this.formData.name;
          this.currentOrg = this.formData.deptId;
          let deptOption = [
            {
              label: this.formData.deptName,
              value: this.formData.deptId,
              id: this.formData.deptId,
            },
          ];
          let locationOption = [
            {
              label: this.formData.locationName,
              value: this.formData.locationId,
              id: this.formData.locationId,
            },
          ];
          setTimeout(() => {
            this.$refs.basicForm.setItemOption("deptName", deptOption);
            this.$refs.basicForm.setItemOption("locationName", locationOption);
            this.$refs.basicForm.setFormItem("deptArr", this.formData.deptId);
            this.$refs.basicForm.setFormItem(
              "locationArr",
              this.formData.locationId
            );
          }, 100);
          if (this.formData.staffType == "3") {
            this.$refs.basicForm.setItemArrRules({
              locationArr: {
                required: false,
              },
            });
          } else {
            this.$refs.basicForm.setItemArrRules({
              locationArr: {
                required: true,
                message: "请选择值班地点",
                trigger: "blur",
              },
            });
          }
          this.setScheduleStatus();
        }
      });
    },
    //设置排班方案状态
    setScheduleStatus() {
      if (this.formData.status == "1") {
        this.statusName = "停用";
        this.statusColor = "#999999";
        if (
          this.formData.shiftList.length != 0 &&
          this.formData.shiftList[0][0].status != 0
        ) {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
        }
        this.basicConfig.itemArr[6].disabled = false;
      } else {
        this.statusName = "启用";
        this.statusColor = "#00BA83";
        if (
          this.formData.shiftList.length != 0 &&
          this.formData.shiftList[0][0].status != 0
        ) {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
        }
        this.basicConfig.itemArr[6].disabled = false;
      }
    },
    //删除
    deleteId() {
      if (this.allowDelete()) {
        this.$confirm("确定要删除排班方案吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonClass:"confirmBtn",
          type: "warning",
        })
          .then(() => {
            deleteSchedulPlan({ id: this.formData.id }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.description);
                this.$utils.addOperateLog(this.formData.id, "删除了排班方案");
                this.updateListData();
                this.$refs.editPage.closePage();
              }
            });
          })
          .catch((e) => {});
      } else {
        this.$alert("排班方案正在运行，请勿删除", "", {
          confirmButtonText: "确定",
          center: true,
        });
      }
    },
    //判断方案是否可以删除
    allowDelete() {
      if (this.formData.shiftList.length == 0 || this.formData.status == 1) {
        return true;
      } else {
        let len = this.formData.shiftList.length - 1;
        let lng = this.formData.items.length - 1;
        return (
          this.formData.shiftList[0][0].status == 0 ||
          this.formData.shiftList[len][lng].status == 2
        );
      }
    },
    //判断是否有重复的排班方案
    async isHaveSameSchedule(type) {
      try {
        let formData = await this.$refs.basicForm.getFormData();
        if (type == "启用") {
          formData.status = 0;
        }
        if (
          formData.locationName == undefined ||
          formData.locationName == "" ||
          !formData.locationName
        ) {
          formData.locationId = "-";
        }
        formData.shiftList = this.$refs.scheduleDetailList.getTableData();
        formData.name = this.titleName;
        let res;
        if (formData.shiftList && formData.shiftList.length == 0) {
          this.$message.warning("排班明细不能为空");
        } else if (!formData.shiftList) {
          this.$message.warning("排班明细未填写完整");
        } else {
          let res = await hasDuplicate(formData);
          if (res.data.length == 0) {
            this.save(formData, type);
          } else {
            this.formData = formData;
            this.scheduleList = res.data;
            this.show = true;
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
    doSubmit() {
      this.save(this.formData);
      this.show = false;
    },
    //点击查看
    clickQuery(item) {
      this.goDetailPage(item.id, "scheduleDetails", "edit");
    },
    //跳转到详情页
    goDetailPage(id, router, type) {
      const { href } = this.$router.resolve({
        name: router,
        query: {
          id: id ? id : "",
          pageType: type ? type : "",
        },
      });
      window.open(href, "_blank");
    },
    //停用排班方案
    async stopPlan() {
      this.$confirm("确定要停用排班方案吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let params = {
            id: this.formData.id,
            status: 1,
          };
          let res = await stopOrStartSchedulPlan(params);
          this.$utils.addOperateLog(this.formData.id, "停用了排班方案");
          //this.$message.success(res.description);
          this.$alert("排版方案正在停用，请在10秒之后再进行其他操作", "", {
            confirmButtonText: "确定",
            center: true,
          });
          this.allowTime();
          this.getDetails(this.formData.id);
        })
        .catch((e) => {});
    },
    //启用排班方案
    async StartPlan() {
      this.$confirm(
        "启用排班方案会保存最新的数据，确定要启用排班方案吗",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.isHaveSameSchedule("启用");
        })
        .catch((e) => {});
    },
    //允许交班时间
    allowTime() {
      this.disableHandover = true;
      this.defaultTime = 10;
      this.timerInterval = setInterval(() => {
        this.computedTime();
      }, 1000);
    },
    //计算时间
    computedTime() {
      let times = this.defaultTime;
      let h = parseInt((times / 60 / 60) % 24); //时
      h = h < 10 ? "0" + h : h; //不足补0
      let m = parseInt((times / 60) % 60); // 分
      m = m < 10 ? "0" + m : m;
      let s = parseInt(times % 60); // 当前的秒
      s = s < 10 ? "0" + s : s;
      this.remainingTime = `${h}:${m}:${s}`;
      this.defaultTime --;
      if (times <= 0) {
        this.disableHandover = false;
        clearInterval(this.timerInterval);
      }
    },
    //保存
    async save(formData, type) {
      try {
        let res = await addOrUpdateSchedulPlan(formData);
        if (type == "启用") {
          this.$utils.addOperateLog(this.formData.id, "启用了排班方案");
        } else {
          this.$utils.addOperateLog(this.formData.id, "修改了排班方案");
        }
        this.$message.success(res.description);
        this.getDetails(this.formData.id);
        this.updateListData();
      } catch (error) {
        console.log(error);
      }
    },
    async multiplexingSubmit(){
      let formData = await this.$refs.copyDialog.getFormData()
      console.log(formData);
      let res = await addOrUpdateSchedulPlan(formData);
      this.goDetailPage(res.data, "scheduleDetails", "edit");
      this.showMultiplexing = false;
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
.dayInput {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wraning {
  min-height: 200px;
  ul {
    margin-top: 20px;
    .text {
      cursor: pointer;
      color: #0d60b4;
      text-decoration: underline;
    }
  }
}
.patCircle {
  display: inline-block;
  width: 60px;
  height: 20px;
  line-height: 20px;
  border-radius: 15px;
  border: 1px solid rgba(223, 223, 223, 0.568);
  color: #f7f7f7;
  margin-left: 10px;
}
.scheduleList {
  height: 530px;
}

</style>
